<template>
    <page-wrap>
        <template #extension>
            <z-search v-model="queryVal" placeholder="请输入您要搜索的商品" @update:model-value="onQuery"></z-search>
            <div class="order-tab">
                <z-tab v-model:active="tabActive" :tabList="tabList" top="2" :border="false"
                    @click-tab="onClickTab"></z-tab>
            </div>
        </template>
        <z-empty type="data" v-if="!shopList.length" />
        <div class="order-container" v-else>
            <z-sidebar :current-active="menuActive" :menu-list="shopList" @click="onSidebar" />
            <div class="order-content-wrapper" ref="scrollContainer" @scroll="onScroll">
                <div class="order-content-wrapper-scroll">
                    <div class="cm-order-group" v-for="groupV, groupIndex in shopList" :key="groupIndex">
                        <div class="cm-order-group-heading">
                            <div class="cm-order-group-title">{{ groupV.name }}</div>
                        </div>
                        <div class="cm-order-group-listbox">
                            <ul class="cm-order-group-list">
                                <li class="cm-product" v-for="v, k in groupV.children" :key="k">
                                    <div class="cm-order-group__cover">
                                        <img class="cm-order-group_img" :src="v.attachment " @error="$event.target.src = defutImage" />
                                        <div class="cm-product-overlay" v-if="v.state == 0">
                                            <div class="cm-product-overlay__text">已下架</div>
                                        </div>
                                        <div class="cm-product-overlay" v-if="v.state == 1 && v.isEstmClear == 1">
                                            <div class="cm-product-overlay__text">已沽清</div>
                                        </div>
                                        <img class="jinbi-img" src="https://oss.jtmckj.com/wmp/qnjg/signin/jinbi-h5.png" alt="">
                                    </div>
                                    <div class="cm-product-info">
                                        <div class="cm-order-group__title">
                                            <div class="cm-order-group__desc">
                                                <span class="cm-order-type-tag combo" v-if="v.type == 1">套餐</span>
                                                <span class="cm-order-type-tag single" v-else>单品</span>
                                                {{ v.goodsName }}({{ v.uomName }})
                                            </div>
                                        </div>
                                        <div class="cm-order-group__money">
                                            <span class="cm-order-group__face">￥{{ v.salePrice }}</span>
                                            <span class="cm-order-group__original">￥{{ v.suggestPrice }}</span>
                                        </div>
                                        <div :class="{ 'cm-product-control': true, 'single': v.state == 0 }">
                                            <div class="cm-product-btn" v-has-role="'waiter-goods-shelves'" v-if="v.state == 1" @click="onShowDown(v)">下架</div>
                                            <div class="cm-product-btn" v-has-role="'waiter-goods-shelves'" v-if="v.state == 0" @click="onConfirmDelist(v)">上架
                                            </div>
                                            <div class="cm-product-btn" v-has-role="'waiter-goods-guqing'" v-if="v.state == 1 && v.isEstmClear == 0"
                                                @click="onShowSellout(v)">沽清</div>
                                            <div class="cm-product-btn lighthigh" v-has-role="'waiter-goods-guqing'" v-if="v.state == 1 && v.isEstmClear == 1"
                                                @click="onConfirmSellout(v)">反沽清</div>
                                        </div>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </page-wrap>
    <!-- 下架提示 -->
    <z-dialog v-model:show="delistShow" @confirm="onConfirmDelist" align="left" title="下架提示"
        content="是否确认下架该菜品？下架后该菜品将不在客户扫码点单中显示！"></z-dialog>
    <!-- 沽清提示 -->
    <z-dialog v-model:show="selloutShow" @confirm="onConfirmSellout" align="left" title="估清提示"
        content="是否确认估清该菜品？"></z-dialog>
</template>
<script setup>
import { showToast } from 'vant'
import { transformArrayProps } from '@/lib/util.js'
import useConfigStore from '@/store/config'
import Api from '@/api'
import _ from 'lodash'

const configStore = useConfigStore()
//图片加载失败显示的默认图片
const defutImage = ref('https://oss.jtmckj.com/wmp/qnjg/signin/product_defutImage.png')
// 提交表单
const postForm = reactive({

})
const router = useRouter()
const tabActive = ref(0)
const menuActive = ref(0);
const tabList = [{
    name: '在售',
}, {
    name: '已下架',
}, {
    name: '已沽清',
}]

const onClickTab = (e) => {
    shopType.value = e.name
}

// 选中商品
const selectedShop = ref([])

// 点击下架
const onShowDown = (product) => {
    selectedShop.value = product
    delistShow.value = true
}
// 确认下架弹窗
const delistShow = ref(false)
// 确认上下架
const onConfirmDelist = (product) => {
    const params = product ? product : unref(selectedShop)
    const { goodsCode, uomCode, state } = params
    Api.Common.AppObjProcess.Do({
        "functionName": "GoodsUpDownShelves",
        "contentData": {
            goodsCode,
            uomCode,
            // 传要改变的状态
            state: state == 1 ? '0' : '1'
        }
    }).then(res => {
        if (state == 1) {
            showToast('下架成功')
        } else {
            showToast('上架成功')
        }
        queryVal.value = ''
        delistShow.value = false
        configStore.Update('goodsList')
        getShopList()
    })
}

// 点击沽清
const onShowSellout = (product) => {
    selectedShop.value = product
    selloutShow.value = true
}
// 确认沽清弹窗
const selloutShow = ref(false)
// 确认沽清反沽清
const onConfirmSellout = (product) => {
    const params = product ? product : unref(selectedShop)
    const { goodsCode, uomCode, isEstmClear } = params
    Api.Common.AppObjProcess.Do({
        "functionName": "GoodsGuQing",
        "contentData": {
            goodsCode,
            uomCode,
            // 传要改变的状态
            state: isEstmClear == 1 ? '0' : '1'
        }
    }).then(res => {
        if (isEstmClear == 0) {
            showToast('沽清成功')
        } else {
            showToast('反沽清成功')
        }
        queryVal.value = ''
        selloutShow.value = false
        configStore.Update('goodsList')
        getShopList()
    })
}

const queryVal = ref('')
// 搜索
const onQuery = function (val) {
    const matchingItems = [];
    unref(historyShopList).forEach((item) => {
        const clonedItem = { ...item }; // 克隆原始对象
        const children = item.children;
        const matchingChildren = children.filter((child) => child.goodsName.includes(val));
        if (matchingChildren.length === 0) {
            return null;
        }
        clonedItem.children = matchingChildren;
        matchingItems.push(clonedItem);
    });
    shopList.value = matchingItems
    setTimeout(() => {
        menuActive.value = 0
        if (scrollContainer.value) {
            scrollContainer.value.scrollTop = 0
        }
    }, 10)
}


const shopType = ref(0)
const allShopList = ref([])
const historyShopList = ref([])
const shopList = ref([])
watch(shopType, (nVal) => {
    shopList.value = filterArray(unref(allShopList), nVal)
    historyShopList.value = filterArray(unref(allShopList), nVal)
    setTimeout(() => {
        menuActive.value = 0
        if (scrollContainer.value) {
            scrollContainer.value.scrollTop = 0
        }
    }, 10)
})
const filterArray = (arr, type) => {
    const filteredArr = arr.reduce((result, item) => {
        const filteredChildren = item.children.filter(child => {
            if (
                (type === 0 && child.state === "1") ||
                (type === 1 && child.state === "0") ||
                (type === 2 && child.state === "1" && child.isEstmClear === "1")
            ) {
                return true;
            }
            return false;
        });

        if (filteredChildren.length > 0) {
            result.push({
                code: item.code,
                name: item.name,
                children: filteredChildren
            });
        }

        return result;
    }, []);

    return filteredArr;
};

const getShopList = async () => {
    const resp = await Api.Common.AppObjProcess.Do({ "functionName": "GetGoodsList", "contentData": { "goodsName": "" } })
    const trans = [
        ['goodsTypeName', 'name'],
        ['goodsTypeCode', 'code'],
        ['goodsList', 'list']
    ]
    const parent = transformArrayProps(configStore.categoryList, trans)
    const child = resp.result
    const arr = [];
    for (let i = 0; i < parent.length; i++) {
        const code = parent[i].code;
        const matchingObjects = child.filter(obj => obj.goodsType === code);
        const newObject = { code, name: parent[i].name, children: [] };
        matchingObjects.forEach(obj => {
            newObject.children.push(obj);
        });
        arr.push(newObject);
    }
    // console.log(arr)
    allShopList.value = _.cloneDeep(arr)
    shopList.value = filterArray(arr, unref(shopType))
    console.log(shopList.value);
    historyShopList.value = filterArray(arr, unref(shopType))
}

const onInit = () => {
    getShopList()
}
onInit()

// 滚动联动
const scrollContainer = ref(null)
const onScroll = function () {
    const parentRect = unref(scrollContainer).getBoundingClientRect();
    // 获取所有锚点元素
    const navContents = document.querySelectorAll('.order-content-wrapper .cm-order-group')
    // 所有锚点元素的 offsetTop
    const offsetTopArr = []
    navContents.forEach((item) => {
        const childRect = item.offsetTop;
        const distance = Math.round(item.offsetTop - parentRect.top);
        offsetTopArr.push(distance);
    })
    // 获取当前文档流的 scrollTop
    const scrollTop = unref(scrollContainer).scrollTop
    // 定义当前点亮的导航下标
    let navIndex = 0
    for (let n = 0; n < offsetTopArr.length; n++) {
        // 如果 scrollTop 大于等于第 n 个元素的 offsetTop 则说明 n-1 的内容已经完全不可见
        // 那么此时导航索引就应该是 n 了
        if (scrollTop >= offsetTopArr[n]) {
            navIndex = n
        }
    }
    menuActive.value = navIndex
}
const onSidebar = function (code, k) {
    // console.log(code,k)
    const parentRect = unref(scrollContainer).getBoundingClientRect();
    // 获取目标的 offsetTop
    // css选择器是从 1 开始计数，我们是从 0 开始，所以要 +1
    const childRect = document.querySelector(`.order-content-wrapper .cm-order-group:nth-child(${k + 1})`)
    const distance = childRect.offsetTop - parentRect.top;
    const targetOffsetTop = Math.round(distance)
    scrollContainer.value.scrollTop = targetOffsetTop
}
</script>
<style scoped lang="scss">
.order-container {
    display: flex;
    height: 100%;
    overflow: hidden;

    .order-content-wrapper {
        padding: 0 11px;
        flex: 1;
        overflow-y: auto;

        &-scroll {
            overflow-y: auto;
        }

    }
}
.cm-order-group__cover{
    position: relative;
    width: 100px;
    height: 100px;
    .cm-product-overlay {
        width: 100px;
        height: 100px;
    }
    .cm-order-group_img {
        width: 100px;
        height: 100px;
        border-radius: 8px 8px 0px 0;
    }
    .jinbi-img {
        position: absolute;
        right: 0px;
        width: 24px;
        height: 12px;
        float: right;
        opacity: 0.8;
    }
}
.cm-order-group .cm-product-control{
    padding-top: 30.5px;
}
@media (min-width: 700px) {
   .cm-order-group .cm-product-control{
    justify-content: start !important;
    .cm-product-btn {
        margin-right: 15px !important;
    }
}
  }
.cm-product-overlay {
    border-radius:0 ;
}
</style>